iT邦幫忙

0

Day10回測模組

d10
  • 分享至 

  • xImage
  •  
 # 可視化預測結果
        if visualize and df is not None:
            plot_predictions(df, y_test, y_pred, test_index, 
                     title=f"Predictions vs Actual (Split {split_num})")
            backtest_strategy(df, y_test, y_pred, test_index)
# -------------------------
# Step 7:回測模組
# -------------------------
def backtest_strategy(df, y_true, y_pred, test_index, initial_capital=10000):
    """
    簡單回測:用模型預測做交易,計算資金曲線
    :param df: 原始 DataFrame (含 close)
    :param y_true: 測試集真實標籤
    :param y_pred: 模型預測結果
    :param test_index: 測試集索引
    :param initial_capital: 初始資金
    """
    df_test = df.iloc[test_index].copy()
    df_test['True'] = y_true
    df_test['Pred'] = y_pred

    capital = initial_capital
    equity_curve = [capital]

    for i in range(1, len(df_test)):
        price_prev = df_test['close'].iloc[i-1]
        price_now = df_test['close'].iloc[i]

        # 真實報酬率
        ret = (price_now / price_prev) - 1

        # 策略報酬率(依照預測方向)
        if df_test['Pred'].iloc[i-1] == 1:  # 預測漲 → 做多
            strategy_ret = ret
        else:  # 預測跌 → 做空
            strategy_ret = -ret

        # 更新資金
        capital *= (1 + strategy_ret)
        equity_curve.append(capital)

    # 存到 DataFrame
    df_test['Equity'] = equity_curve

    # 畫圖
    plt.figure(figsize=(12,6))
    plt.plot(df_test['timestamp'], df_test['Equity'], label="Equity Curve", color="blue")
    plt.axhline(initial_capital, linestyle="--", color="gray", alpha=0.7)
    plt.title("Backtest Equity Curve")
    plt.xlabel("Time")
    plt.ylabel("Capital")
    plt.legend()
    plt.xticks(rotation=45)
    plt.show()

    # 總績效
    total_return = (capital / initial_capital - 1) * 100
    print(f"💰 最終資金: {capital:.2f} USDT")
    print(f"📈 總報酬率: {total_return:.2f}%")

    return df_test


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言